//
//  IcoLabel.swift
//  HLDesktop
//
//  Created by 黄龙 on 2023/8/23.
//

import UIKit

class IcoLabel: UIView, CAAnimationDelegate {
    // #imageLiteral(resourceName: "app_default@2x.png")
    // #colorLiteral(red: 0.501960814, green: 0.501960814, blue: 0.501960814, alpha: 0.75)
    lazy var icoView: UIImageView = {
        let imgView = UIImageView()
        imgView.image = #imageLiteral(resourceName: defaultIcoLogo) //UIImage(named: defaultIcoLogo)
        imgView.contentMode = .scaleToFill
        imgView.layer.cornerRadius = 12
        imgView.clipsToBounds = true
        return imgView
    }()
    
    lazy var icoDel: UIButton = {
        let imgView = UIButton()
        imgView.setImage(UIImage(named: "appDel@2x.png")!, for: .normal)
        imgView.layer.cornerRadius = 12
        imgView.backgroundColor = .systemGray.withAlphaComponent(0.75)
        return imgView
    }()
    
    lazy var icoModi: UIButton = {
        let imgView = UIButton()
        imgView.setImage(UIImage(named: "appCfg@2x.png")!, for: .normal)
        imgView.backgroundColor = .systemGray.withAlphaComponent(0.75)
        imgView.layer.cornerRadius = 12
        return imgView
    }()
    
    lazy var titleLabel: UILabel = {
        let label = UILabel()
        label.font = .systemFont(ofSize: 12)
        label.textColor = .white
        label.textAlignment = .center
        label.text = "呵呵"
        return label
    }()
    
    public var didSeletedBlock: os_block_t? //长按编辑
    public var didTapBlock: os_block_t? //点击
    public var doModiBlock: os_block_t? //编辑按钮
    public var doDeleteBlock: os_block_t? //编辑按钮
    
//    public var moveingBlock: os_block_t? //移动
//    public var moveEndBlock: os_block_t?
//    public var moveCancelBlock:os_block_t?
    typealias os_block_state = (_ state:Int) -> Void //0->end,1-begin,2->begin.move,3-moving //3种触发顺序：begin->cancel / begin->moving->end(or cancel)
    public var touchStateBlock: os_block_state?
    var iState:Int = 0 //0->end(cancel),1-begin,2->beginmove,3-moving
    var lastLocation:CGPoint = CGPoint(x: 0, y: 0)
    var lastPage:Int = 0 //所属桌面Page
//or
//    public var touchStateBlock:((_ state:Int)->Void)?
    var forbidMoveToAnotherPage:Bool = true //禁止跨页移动
    
    
    private var isLongPressed:Bool = false
    
//格式url=appbid&|&storelink=&|&title=&|&icon=
    private var appbid:String = "" //打开命令
    private var storelink:String = ""
    private var iconUrl:String = ""
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        self.initUI()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func initUI(){
        self.addSubview(icoView)
        icoView.frame = CGRect(x: frame.width/2-64/2, y: 0, width: 64, height: 64)
        
        self.addSubview(titleLabel)
        titleLabel.frame = CGRect(x: 0, y: frame.height-12, width: frame.width, height: 12)
        titleLabel.setShadow(shadowColor: .black, offset: CGSize(width: -3,height: -3), opacity: 0.75, radius: 6)
        
        self.addSubview(icoDel)
        icoDel.frame = CGRect(x: -4, y: -4, width: 24, height: 24)
        icoDel.isHidden = true
        icoDel.addActionWithBlock { sender in
            self.doDeleteBlock?()
        }
        
        self.addSubview(icoModi)
        icoModi.frame = CGRect(x: self.bounds.width-20, y: -4, width: 24, height: 24)
        icoModi.isHidden = true
        icoModi.addActionWithBlock { sender in
            self.doModiBlock?()
        }
        
        let longPress = UILongPressGestureRecognizer(target: self, action: #selector(handleLongPress(longPress:)))
       //        longPress.numberOfTapsRequired 长按之前要轻点几下
        self.addGestureRecognizer(longPress)
        
        let tapView = UITapGestureRecognizer(target: self, action: #selector(tapApp))
        self.addGestureRecognizer(tapView)
    }
    
    @objc func tapApp(){
        if !isLongPressed{
            didTapBlock?()
        }
    }
    
    func setTitle(title:String){
        titleLabel.text = title
    }
    
    func title()->String{
        return titleLabel.text!
    }
    
    func setImage(imgName:String){
        self.iconUrl = imgName
        icoView.setImageWithStr(imgurl: imgName,defName: defaultIcoLogo)
    }
    
    func relaodAppIco(){
        icoView.setImageWithStr(imgurl: self.iconUrl,defName: defaultIcoLogo)
    }
    
    func iconurl()->String{
        return self.iconUrl
    }
    
    func setAppBid(bid:String){
        self.appbid = bid
    }
    
    func appBid()->String{
        return self.appbid
    }
    
    func setStoreLink(link:String){
        self.storelink = link
    }
    
    func storeLink()->String{
        return self.storelink
    }
    
    @objc func handleLongPress(longPress: UILongPressGestureRecognizer) {
        if longPress.state == .began {
            isLongPressed = true
//振动音效
//            playVibrate(iVibrate: 1)
            Vibrations.light.vibrate()
            
            let shakeValue = Double.pi/72.0
            self.layer.add(self.shakeAnimate(repeatCount: MAXFLOAT, duration: 0.25,autoRev: true, values: [-shakeValue, shakeValue,-shakeValue]), forKey: "tapShake")
            self.icoDel.isHidden = false
            self.icoModi.isHidden = false
            didSeletedBlock?()
//            didLongTapBlock?(true)
        }else if longPress.state == .ended{
//            NSLog("longPress.ended")
        }else if longPress.state == .changed{
//            NSLog("longPress.changed")
        }else if longPress.state == .cancelled{
//            NSLog("longPress.cancelled")
        }
    }
    
    
    override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
        if isLongPressed{
            //获取手指
            let touch = (touches as NSSet).anyObject() as! UITouch
            let nowLocation = touch.location(in: self)
            let preLocation = touch.previousLocation(in: self)
            
            //获取两个手指的偏移量
            let offsetX = nowLocation.x - preLocation.x
            let offsetY = nowLocation.y - preLocation.y
            
            var center = self.center
            center.x += offsetX
            center.y += offsetY
//-----禁止跨屏移动？
            if forbidMoveToAnotherPage{
                if center.x - self.bounds.width/2 < 0{
                    center.x = self.bounds.width/2
                }else if center.x + self.bounds.width/2 > screen_W{
                    center.x = screen_W - self.bounds.width/2
                }
                
                if center.y - self.bounds.height/2 < 0{
                    center.y = self.bounds.height/2
                }else if center.y + self.bounds.height/2 > superview!.bounds.height{
                    center.y = superview!.bounds.height - self.bounds.height/2
                }
            }
//-----------
            self.center = center
//            moveingBlock?()
            if 1 == iState{
                print("....beginmove")
                iState = 2
                touchStateBlock?(iState) //only.noti：begin-Move
            }else if iState >= 2 {
//                print("location:\(nowLocation)")
                iState = 3
                touchStateBlock?(iState) //moving
            }
                
        }
    }
    
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        print("....touchesBegan") //touchesBegan+首次move，说明开始移动
        if isLongPressed {
            iState = 1
            lastLocation = self.center
            touchStateBlock?(iState)
        }
    }
    
    override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
        print("....touchesEnded")
        if isLongPressed {
            if iState >= 2{//只移动过之后的结束才需要处理
                iState = 0
                touchStateBlock?(iState) //只在结束时通知，以便主UI做自动对齐吸附等动作即可
            }
        }
    }
    
    override func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?) {
        print("....touchesCancelled")//还没移动就抬起来了，即触发touchesCancelled
        if isLongPressed{//只移动过之后的结束才需要处理
            if 3 == iState{
                iState = 0
                touchStateBlock?(iState)
            }
        }
    }
    
    
    /// 直接实现
        /// - Parameters:
        ///   - repeatCount: 重复次数
        ///   - duration: 持续时间
        ///   - values:  //抖动幅度数组：不需要太大：从-15度 到 15度、再回到原位置、为一个抖动周期
        /// - Returns: 返回动画 CAKeyframeAnimation
    func shakeAnimate(repeatCount:Float,duration:CFTimeInterval,autoRev:Bool,values:[Any]) -> CAKeyframeAnimation {
            let keyAnimation:CAKeyframeAnimation = CAKeyframeAnimation(keyPath: "transform.rotation")
            keyAnimation.delegate = self
            //开始时间
            keyAnimation.beginTime = CACurrentMediaTime()
            //持续时间 0.2
            keyAnimation.duration = duration
     
            keyAnimation.values = values
            //重复次数 3
            keyAnimation.repeatCount = repeatCount
            //完成后是否移除
            keyAnimation.isRemovedOnCompletion = true
            
            keyAnimation.autoreverses = autoRev
            return keyAnimation
        }
    
    func animationDidStop(_ anim: CAAnimation, finished flag: Bool) {
        if flag {
//            self.giftBtn.layer.removeAnimation(forKey: "transform.rotation")
        }
    }
    
    func stopTapAnimate(){
        isLongPressed = false
        self.layer.removeAnimation(forKey: "tapShake")
//        self.layer.removeAllAnimations()
        self.icoDel.isHidden = true
        self.icoModi.isHidden = true
    }
    
    func startTapAnimate(){
        if (!isLongPressed){
            isLongPressed = true
            self.icoDel.isHidden = false
            self.icoModi.isHidden = false
            let shakeValue = Double.pi/72.0
            self.layer.add(self.shakeAnimate(repeatCount: MAXFLOAT, duration: 0.25,autoRev: true, values: [-shakeValue, shakeValue,-shakeValue]), forKey: "tapShake")
        }
    }
    
    
    func enabelEdit(){
        self.icoDel.isHidden = false
        self.icoModi.isHidden = false
        self.stopTapAnimate()
        self.startTapAnimate()
    }
    
}
